<template>
	<view @click.stop="() => {}" v-if="judgeGopayOrQianyue()">
		<view
			:class="{ actionBtn: true, actionBtn0: position == 0, actionBtn1: position == 1, actionBtn2: position == 2, actionBtn3: position == 3 }"
			@click.stop="payHandler">
			{{ btnTxt }}
		</view>
		<PartyCover @partCoverCall="partCoverCall" ref="partCover" />
		<!-- 选择支付方式的时候的弹出框 -->
		<view class="mengceng" v-if="mengcengShow" @click="tab_mengceng" @touchmove.stop.prevent="moveHandle"></view>
		<view class="tankuang" v-if="tankuangShow" @touchmove.stop.prevent="moveHandle">
			<view style="margin: 10rpx 0 5rpx 30rpx">选择支付方式</view>
			<view v-if="zfbHasPayment">
				<view v-show="!zhifubaoCheckedState">
					<image @click="tab_zhifubao" style="width: 100%; height: 140rpx"
						src="@/static/shouye-add-rich/zhifubao1-rich.png" mode="aspectFit"></image>
				</view>
				<view v-show="zhifubaoCheckedState">
					<image @click="tab_zhifubao" style="width: 100%; height: 140rpx"
						src="@/static/shouye-add-rich/zhifubao-rich.png" mode="aspectFit"></image>
				</view>
			</view>
			<view v-if="wxHasPayment">
				<view v-show="!weixinCheckedState">
					<image @click="tab_weixin" style="width: 100%; height: 140rpx"
						src="@/static/shouye-add-rich/weixin1-rich.png" mode="aspectFit"></image>
				</view>
				<view v-show="weixinCheckedState">
					<image @click="tab_weixin" style="width: 100%; height: 140rpx"
						src="@/static/shouye-add-rich/weixin-rich.png" mode="aspectFit"></image>
				</view>
			</view>
			<view class="btn_bottom" @click="btn_comfirm">确定</view>
		</view>
		<view class="bigMengceng" @click="closeMengceng" v-if="isWexinOpenSecondSign">
			<image class="openImg" src="./open.png" mode="aspectFit"></image>
		</view>
	</view>
</template>

<script>
	// 去支付 & 确认支付 按钮
	import {
		checkPosition,
		checkOrderSettleNeedPay,
		notifyTopPageRefresh
	} from '../utils/checkShowBtn.js';
	import {
		go_Myl,
		go_EQian,
		getUserId
	} from '../../../../utils/index.js';
	import {
		getAppId,
		tradePay
	} from '../../../../utils/platform';
	import PartyCover from '../../../partyCover';
	import {
		APP_APPID
	} from '../../../../utils/constant.js';

	export default {
		name: 'quzhifu',
		components: {
			PartyCover
		},
		props: {
			order: {
				type: Object,
				default: {}
			}, // 订单对象
			isUsedInList: {
				type: Boolean,
				default: true
			}, // 是否使用在订单列表页面
			userOrderCashDto: {
				type: Object,
				default: null
			}
		},
		data() {
			return {
				isPaySuipxSta: true,
				isWexinOpenSecondSign: false,
				isWxBrowser: false, //是否在微信浏览器中
				// signValiSta:
				isSignValidate: '2',
				userId: '',
				zfbHasPayment: true,
				wxHasPayment: true,
				mengcengShow: false,
				tankuangShow: false,
				zhifubaoCheckedState: false,
				weixinCheckedState: false,
				uniPlatform: '',
				// #ifdef MP-ALIPAY
				payType: 'alipays',
				// #endif
				// #ifdef MP-WEIXIN
				payType: 'wechat',
				// #endif
				// #ifndef MP
				payType: '',
				// #endif


				//下面是没用的垃圾混淆代码
				renzhengTimeSta1111111: true, //初次请求认证时间默认是带有的，
				zhuceTimeSta11111: false, //初次请求注册时间默认是没有的
				renzhengTimeList11111: [],
				zhuceTimeStaList1111: null,
				detailOrderIdStr11111: '',
				threeTabCurrent1111: 0,
				applyGOodsList11111: [], //供货商列表
				allCardEnterSta1111: false, //默认是false，点击批量卡券入库的时候变为true
				codeAddNumsList11111: [],
				numsList11111: [],
				dataSourceBqcp1111: [],
				selectedRowKeys1111: [],
				selectedRowKeysB11111: [],
				rkVisible11111: false,
				rkjlVisible1111: false,
				lhjlVisible1111: false,
				currentStyleData22222: {},
				dataSourceStyle2222: [],
				showStyleData2222: false,
				indexTemplate2222: [],
				SVGCircleElement3ee: '',
				vshoweqwsc1111: false,
				showStyleDataInfo2222: false,
				opeCategoryList2222: [],
				leimuVisible2222: false,
				selectedRowKeys02222: [],
				selectionRows02222: [],
				selectedRowKeys133333: [],
				selectionRows13333: [],
				selectedRowKeys2333: [],
				selectionRows23333: [],
				selectedRowKeys33333: [],
				selectionRows33333: [],
				selectedRowKeys4333: [],
				selectionRows43333: [],
				curwfqwrentStyleDaterwaInfo444: {},
				currwerentStywerleDatweraInfo1444: {},
				currewerntStyleDataInfo24444: {},
				currentweStyleDytuataIwenfo34444: {},
				currenwetStdfgyleDataInfo44444: {},
				checkZfbPhone_h5444: '',
				plNafgdvfdtjyme4444: '', //四大品类的名字
				uniPdfgrtylatform444: '', //运行环境mp-alipay mp-weixin
				refgjtytrsemark555: '', //备注
				timefgjSelStr5555: '', //选择的上门时间（2023-08-31 00:00:00）
				amOdcuiofasrpm5555: '', //选择的上门时间是上午还是下午
				pageShnjlkgohowTime5555: '', //页面上用户看到的显示的时间
				paraghsdfmsw454: {},
				valhgujtueNum56756: 0,
				addrdraess56756: {}, //上门收货地址
				adawerterydressId575: 0,
				sceoyuitne57567: '',
				tntuiopId56757: '',
				weictyuratCustomer5756: '',
				yuidurtyuoy567567: false,




			};
		},

		computed: {
			position: function() {
				return checkPosition.quzhifu(this.order, this.isUsedInList);
			},
			btnTxt: function() {
				if (checkOrderSettleNeedPay(this.order)) {
					return '确认支付';
				}
				if (this.order.status !== '01' && this.order.antType == '1' && this.order.signState === false && this
					.order.signUrl) {
					return '去签约';
				} else if (this.order.status === '01') {
					return '去支付';
				} else if (this.order.status !== '01' && this.order.antType == '2' && this.order.signStatusType != 2) {
					return '去签约';
				}
			}
		},
		watch: {
			isSignValidate(newValue, oldValue) {
				console.log('==newValue=新值=', newValue);
				console.log('==oldValue=旧值=', oldValue);
				if (newValue == '1') {
					this.goQianyue()
				}
			}
		},
		mounted() {
			this.fetchPeriodList()
			this.judgeBrowserEnv()
			console.log('当前的uid', getUserId());
			this.userId = getUserId()
			this.getPaymentList()
		},

		methods: {
			fetchPeriodList() {
				this.$request(
						`order/mall/api/orderByStages/queryOrderByStagesByOrderId?orderId=${this.order.orderId}`, {},
						'get', true, true)
					.then((res) => {
						let billList = res.data || []
						billList.some(item => {
							if (item.currentPeriods == 0 && item.status != 2 && item.status != 3) {
								//碎屏险还没有支付
								this.isPaySuipxSta = false
								return true
							}
							if (item.currentPeriods == 0 && (item.status == 2 || item.status == 3)) {
								//碎屏险已经支付
								this.isPaySuipxSta = true
								return true
							}
						})
					})
			},
			//是否签约
			goSignVali() {
				this.$request('order/mall/liteUserOrders/signValidate', {
					orderId: this.order.orderId
				}, 'post', false).then((res) => {
					if (res.data == '1') {
						this.goQianyue()
					} else {
						uni.showToast({
							title: '订单异常返回false，请联系客服',
							icon: 'none',
							duration: 3000
						});
					}
				});
			},
			//动态获取用户的支付方式（hlb-合利宝，zfb-支付宝，wx-微信）
			getPaymentList() {
				this.$request('order/mall/components/getPayChannelList', {}, 'get', false).then((res) => {
					if (res.data && res.data.length > 0) {
						this.zfbHasPayment = res.data.some(item => item.type == 'zfb')
						this.wxHasPayment = res.data.some(item => item.type == 'wx')
					}
				});
			},
			//判断去支付或者去签约是否显示按钮
			judgeGopayOrQianyue() {
				//payments:true 带有有要支付的期数（首付）。不显示签约，显示账单
				if (this.order.faceAuthStatus == '03') {
					//此时认证已完成,才能展示账单的东西
					if (!this.order.payments) {
						if (this.order.antType == '1') {
							//旧的
							if ((this.order.status !== '01' && this.order.signState === false && this.order.signUrl) ||
								this
								.order
								.status === '01') {
								return true
							} else {
								return false
							}
						} else {
							if ((this.order.signStatusType == '0' || this.order.signStatusType == '1') && this.order
								.signUrl) {
								return true
							} else {
								return false
							}
						}
					} else {
						return false
					}
				} else {
					return false
				}


			},
			tab_mengceng() {
				this.mengcengShow = false;
				this.tankuangShow = false;
			},
			//先触发选择弹出窗和灰色蒙层  选择支付宝支付还是微信支付
			payHandler() {
				if (this.order.status != '01' && this.order.antType == '1' && this.order.signState === false) {
					// if (this.userId == '28e86b182e7fcba67a2c06dc5b85246cb2dd4773dp7tx9sd4xki') {
					// 	let parObj = {
					// 		orderId: this.order.orderId
					// 	}
					// 	this.$request('order/mall/liteUserOrders/signValidate', parObj, "POST").then(res => {
					// 		if (res.data === '1') {
					// 			this.goQianyue()
					// 		} else {
					// 		}
					// 	})
					// } else {
					// 	this.goQianyue()
					// }
					let parObj = {
						orderId: this.order.orderId
					}
					this.$request('order/mall/liteUserOrders/signValidate', parObj, "POST").then(res => {
						if (res.data === '1') {
							this.goQianyue()
						} else {
							uni.showToast({
								title: '订单状态异常，请联系客服',
								icon: 'none',
								duration: 3000
							});
						}
					})
				} else if (this.order.status != '01' && this.order.antType == '2' && this.order.signStatusType != 2) {
					this.newEQianBaoSignUrl()
				} else {
					//待支付
					// #ifdef H5 || APP-PLUS
					if (!this.weixinCheckedState && !this.zhifubaoCheckedState) {
						this.mengcengShow = true;
						this.tankuangShow = true;
						// uni.showToast({
						// 	icon: 'none',
						// 	title: '请选择支付方式'
						// });
						// return
					}
					// #endif

					// #ifndef H5 || APP-PLUS
					this.payMoneyHandler();
					// #endif
				}
			},
			// 第一次签约和第二次代扣都走这个方法
			newEQianBaoSignUrl() {
				this.$request(
					`order/mall/liteUserOrders/getOrderWithholdSign?orderId=${this.order.orderId}`, {},
					'get', false,
					true).then((res) => {
					if (res.businessSuccess || res.success) {
						if (res.data.status == '0' && res.data.url != '') {
							// this.OneQianYue(res.data.url)

							let flowId = this.order.flowId || ''
							let signerId = this.order.signerId || ''
							let orderId = this.order.orderId
							let jumpZfbUrl = `https://ds.alipay.com/?scheme=` +
								encodeURIComponent(
									`alipays://platformapi/startapp?appId=2021004166678607&page=pages/antSign/antSign&query= ${encodeURIComponent(`flowId=${flowId}&signerId=${signerId}&orderId=${orderId}`)}`
								)
							window.location.href = jumpZfbUrl
						}
						if (res.data.status == '1' && res.data.url != '') {
							//第二份支付宝代扣合同
							// this.newAntToSign(decodeURIComponent(res.data.url))

							let orderId = this.order.orderId
							let type = '123456'
							let jumpZfbUrl = `https://ds.alipay.com/?scheme=` +
								encodeURIComponent(
									`alipays://platformapi/startapp?appId=2021004166678607&page=pages/antSign1/antSign1&query= ${encodeURIComponent(`orderId=${orderId}&type=${type}`)}`
								)
							window.location.href = jumpZfbUrl
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: res.errorMessage || res.msg || '订单异常,请退出重试!',
							duration: 2000
						});
					}
				});
			},
			//第一步的签约
			OneQianYue(signUrl) {
				let isIosEnv = uni.getSystemInfoSync().platform
				if (isIosEnv == 'ios') {
					uni.showLoading({
						title: "加载中"
					})
					let timer1 = null
					timer1 = setTimeout(() => {
						uni.hideLoading()
						window.open(signUrl, "_blank");
						clearTimeout(timer1);
						timer1 = null
					}, 300); // 延迟0.5秒
				} else {
					window.open(signUrl, "_blank");
				}
			},
			// 第二步蚂蚁连代扣
			newAntToSign(urls) {
				let jumpUrl = `https://openapi.alipay.com/gateway.do?${urls}`
				// window.location.href = jumpUrl
				// window.open(jumpUrl, "_blank");
				if (this.isWxBrowser) {
					//在微信环境中不能跳转，打开蒙层，提示在微信中打开
					this.isWexinOpenSecondSign = true
					return
					// window.location.href = jumpUrl
				} else {
					this.isWexinOpenSecondSign = false
					let isIosEnv = uni.getSystemInfoSync().platform
					if (isIosEnv == 'ios') {
						uni.showLoading({
							title: "加载中"
						})
						let timer1 = null
						timer1 = setTimeout(() => {
							uni.hideLoading()
							window.open(jumpUrl, "_blank");
							clearTimeout(timer1);
							timer1 = null
						}, 300); // 延迟0.5秒
					} else {
						window.open(jumpUrl, "_blank");
					}
				}
			},
			closeMengceng() {
				this.isWexinOpenSecondSign = false
			},
			//判断当前浏览器环境
			judgeBrowserEnv() {
				let ua = navigator.userAgent.toLowerCase(); // 这里将所有字母转小写
				let isWxBrowser = ua.indexOf('micromessenger') !== -1
				console.log('微信环境吗', ua.indexOf('micromessenger') !== -1);
				if (ua.indexOf('micromessenger') !== -1) {
					this.isWxBrowser = true
					// this.getWechatCode()
				} else {
					this.isWxBrowser = false
				}
			},




			tab_zhifubao() {
				this.zhifubaoCheckedState = !this.zhifubaoCheckedState;
				this.weixinCheckedState = false;
				this.payType = 'alipays';
			},
			tab_weixin() {
				this.weixinCheckedState = !this.weixinCheckedState;
				this.zhifubaoCheckedState = false;
				this.payType = 'wechats';
			},

			btn_comfirm() {
				if (!this.zhifubaoCheckedState && !this.weixinCheckedState) {
					uni.showToast({
						icon: 'none',
						title: '请选择支付方式'
					});
					return;
				}
				this.mengcengShow = false;
				this.tankuangShow = false;
				this.payMoneyHandler();
			},

			//把签约的方法单独拿出来
			goQianyue() {
				//不等于01：即待签约的单子，下面走的是签约的流程
				if (this.order.esignStatus === 4) {
					uni.showToast({
						title: '已拒签，请联系客服处理',
						icon: 'none'
					});
					return;
				} else {
					//未拒签
					// #ifdef MP-WEIXIN
					uni.showToast({
						title: '下单已完成，请联系客服获取合同链接',
						icon: 'none'
					});

					// #endif

					// #ifndef MP-WEIXIN
					// 0  未签署  2  签署完成   e签宝已签署    4  已拒签
					console.log('签合同前期签签签签', this.order);
					if (this.order.esignUrl && this.order.esignStatus === 0) {
						//有e签宝且未签署
						go_EQian(this.order, {
							platformType: 'h5'
						}, true);
						return;
					}
					if (this.order.signUrl && this.order.esignStatus !== 2) {
						// 有蚂蚁链或者未签署完成
						if (this.order.signUrl.indexOf('alipays') === 0) {
							go_Myl(this.order, {
								platformType: 'alipays'
							}, true);
						} else {
							go_Myl(this.order, {
								platformType: 'h5'
							}, true);
						}
						return true;
					}
					// #endif
				}
			},
			/**
			 * 点击去支付按钮的时候触发
			 */
			payMoneyHandler() {
				// if (this.order.status != '01' && this.order.signState === false) {
				// 	// 
				// 	if (this.userId == '28e86b182e7fcba67a2c06dc5b85246cb2dd4773dp7tx9sd4xki' || this.userId ==
				// 		'428f61ae64ba25bb3b49aeb84799e39c4cea7588k0sbre03vtw9' || this.userId ==
				// 		'c79350173fca164bdceef0307815108c9d85fffftax7bkuysawc' || this.userId ==
				// 		'26858a8a29ddab43ee8f44550aba74733211f8aab8iu5rvqrvyw') {
				// 		this.goSignVali()
				// 	} else {
				// 		this.goQianyue()
				// 	}
				// }
				if (this.order.status == '01') {
					//01是待支付，走支付流程
					const orderId = this.order && this.order.orderId;
					//#ifdef MP-WEIXIN
					const platformType = 'wechat';
					// #endif

					// #ifdef APP-PLUS
					const platformType = 'app';
					// #endif

					// #ifdef H5
					const platformType = 'h5';

					// #endif

					// #ifdef MP-ALIPAY
					const platformType = 'alipay';
					// #endif

					const postObj = {
						orderId,
						platformType,
						payType: this.payType
					};
					const cnMap = {
						orderId: '订单ID',
						platformType: 'platformType',
						payType: '支付方式'
					};
					const {
						postData,
						pass
					} = this.$postDataGuard(postObj, cnMap);
					if (!pass) return;
					let url = 'order/mall/api/order/userFreezeAgain';
					const isJiesuan = checkOrderSettleNeedPay(this.order);
					if (isJiesuan) {
						let v;
						if (this.userOrderCashDto) v = this.userOrderCashDto.settlementRent;
						else v = this.order.settlementRent;
						postData.amount = v;
						url = 'order/mall/api/order/settlement/liteUserPaySettlement';
					}
					this.$request(url, postData, 'POST').then((res) => {
						const resData = res.data || {};
						let data;
						if (isJiesuan) data = [resData.payUrl, true]; // 结算待支付时的支付
						else data = [resData.freezeAgainUrl];

						uni.showLoading({
							title: '加载中'
						});
						// #ifdef MP-WEIXIN
						if (res.data.freezeUrl == null && res.data.wechatOrderMap == null) {
							var that = this;
							uni.hideLoading();
							uni.showModal({
								title: '温馨提示',
								content: '订单已生成，请耐心等待平台审核!',
								success: function(res) {
									if (res.confirm) {
										that.partCoverCall();
										console.log('用户点击确定');
									} else if (res.cancel) {
										that.partCoverCall();
										console.log('用户点击取消');
									}
								}
							});
						} else if (res.data.wechatOrderMap) {
							var that = this;
							wx.requestPayment({
								timeStamp: res.data.wechatOrderMap.timeStamp, //时间戳
								nonceStr: res.data.wechatOrderMap.nonceStr, //随机字符串
								package: res.data.wechatOrderMap.package,
								signType: 'RSA', //签名算法
								paySign: res.data.wechatOrderMap.paySign, //签名
								success: function(res) {
									uni.hideLoading();
									setTimeout(() => {
										uni.showToast({
											icon: 'none',
											title: '支付成功'
										});
									}, 100); // 加入一点延时，避免后端接收支付宝回调不及时。若不需要，那去掉延时
									notifyTopPageRefresh.apply(this);
								},
								fail: function(err) {
									uni.hideLoading();
									console.log('支付失败');
									setTimeout(() => {
										uni.showToast({
											icon: 'none',
											title: '支付失败'
										});
									}, 100);
									notifyTopPageRefresh.apply(this);
								},
								complete: function(res) {
									uni.hideLoading();
									console.log('支付完成');
								}
							});
						}
						// #endif

						// 二、非微信（ (app zfb)  h5 ）小程序内走的方法
						// #ifndef MP-WEIXIN
						var that = this;
						if (!!res.data.freezeAgainUrl) {
							let useTradeSta = !res.data.serialNo ? true : false;
							// 2.1  (app zfb)内走的方法
							// #ifndef H5
							tradePay(...data, useTradeSta)
								.then((res) => {
									var that = this;
									if (res.resultCode === '9000') {
										uni.hideLoading();
										setTimeout(() => {
											uni.showToast({
												title: '支付成功'
											});
										}, 1000);
										notifyTopPageRefresh.apply(this);
									}
									if (res.resultCode === '6001') {
										uni.hideLoading();
										setTimeout(() => {
											uni.showToast({
												icon: 'none',
												title: '用户取消支付'
											});
										}, 1000);
										notifyTopPageRefresh.apply(this);
									}
									if (res.channel.serviceReady) {
										uni.hideLoading();
										setTimeout(() => {
											uni.showToast({
												title: '支付成功'
											});
										}, 1000);
										notifyTopPageRefresh.apply(this);
									}
								})
								.catch(() => {
									// 支付失败||取消支付
								});
							// #endif
							// #ifdef H5
							//h5支付宝支付走的
							window.location.href = res.data.freezeAgainUrl;
							// #endif
						} else {
							if (that.weixinCheckedState && res.data.wechatOrderMap) {
								window.location.href = res.data.wechatOrderMap.h5_url;
							}
						}
						// #ifdef APP-PLUS
						// app的微信付款
						if (that.weixinCheckedState && res.data && res.data.wechatOrderMap) {
							console.log('==========weixinzhifu:', res);
							uni.requestPayment({
								provider: 'wxpay',
								orderInfo: {
									appid: res.data.wechatOrderMap
										.appid, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
									noncestr: res.data.wechatOrderMap.nonceStr, // 随机字符串
									package: res.data.wechatOrderMap.packageVal, // 固定值
									partnerid: res.data.wechatOrderMap.partnerId, // 微信支付商户号
									prepayid: res.data.wechatOrderMap.prepayId, // 统一下单订单号
									timestamp: res.data.wechatOrderMap.timestamp, // 时间戳（单位：秒）
									sign: res.data.wechatOrderMap.sign // 签名，这里用的 MD5/RSA 签名
								}, //此处为服务器返回的订单信息字符串
								success: function(res) {
									uni.hideLoading();
									setTimeout(() => {
										uni.showToast({
											icon: 'none',
											title: '支付成功'
										});
										notifyTopPageRefresh.apply(this);
									}, 1500);
								},
								fail: function(err) {
									console.log('支付失败:' + JSON.stringify(err));
									notifyTopPageRefresh.apply(this);
								}
							});
						}
						// #endif
						// #endif
					});
				}
			},
			partCoverCall() {
				notifyTopPageRefresh.apply(this);
			}
		}
	};
</script>

<style>
	.bigMengceng {
		display: flex;
		justify-content: flex-end;
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 100vh;
		z-index: 999999;
		background: rgba(76, 76, 76, 0.9);
	}

	.openImg {
		width: 240rpx;
		height: 160rpx;
		display: block;
		margin: 20rpx 30rpx 0 0;
	}

	.actionBtn {
		width: 138rpx;
		height: 56rpx;
		border-radius: 30rpx;
		border: 1px solid #c0c0c0;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #666666;
		margin-left: 24rpx;
		flex-shrink: 0;
		float: right;
		// position: absolute;
	}

	.actionBtn {
		position: relative;
	}

	.tankuang {
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 150;
		width: 100%;
		height: 600rpx;
		background-color: white;
	}

	.btn_bottom {
		width: 94%;
		letter-spacing: 10rpx;
		height: 80rpx;
		position: absolute;
		bottom: 50rpx;
		left: 50%;
		transform: translateX(-50%);
		border-radius: 10rpx;
		line-height: 80rpx;
		text-align: center;
		color: white;
		background-color: #1777ff;
	}

	.mengceng {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 100vh;
		z-index: 100;
		opacity: 0.5;
		/* background-color: #999999; */
		background-color: #4b2323;
	}
</style>